<?php
/*
** date : 2011-1-21 ; copyright : 7OUR.COM <http://7our.com> ; author : xjay <xucj21@21cn.com>
*/
class UserModel extends Model {
	protected $_validate = array(
		array('email','email','邮箱格式不正确'),
		array('email','','您输入的邮箱账号已被注册！',1,'unique',1),
		array('username','','您输入的用户名已被注册！',1,'unique',1),	
		array('ckpwd','password','您两次输入的密码不一致！',1,'confirm'),	
	);
	protected $_auto = array(
		array('password','md5',1,'function'),	//密码加密
		array('ctime','time',1,'function'),		//创建时间
		array('cip','getIp',1,'callback'),		//创建IP
	);

	//登录验证
	public function doLogin($data){
		// 表单令牌验证
        if(C('TOKEN_ON') && !$this->autoCheckToken($data)) {
        	$this->error = L('_TOKEN_ERROR_');
            return false;
        }
        $vo = $this->where(array('email'=>$data['email'],'status'=>'1'))->find();
        if(!empty($vo['id'])&&$vo['password'] == md5($data['password'])){
        	$vo['lastlogintime'] = time();
        	$vo['lastloginip'] = $this->getIp();
        	$this->save($vo);
        	unset($vo['password']);
        	Session::set('web_user',serialize($vo));
        	return true;
        }else{
        	$this->error = L('_LOGIN_ERR_UORP_');
        	return false;
        }
	}
	//判断是否登录
	public function isLogin(){
		$user = $this->getLoginUser();
		return !is_null($user);
	}
	//获取登录用户
	public function getLoginUser(){
		$sess = Session::get('web_user');
		$user = $sess?(array)unserialize($sess):null;
		return $user;
	}
	//获取登录用户的ID
	public function getLoginUserId(){
		$user = $this->getLoginUser();
		return $user['id'];
	}
	//获取登录用户的用户名
	public function getLoginUserName(){
		$user = $this->getLoginUser();
		return $user['username'];
	}
	//获取登录用户的域名
	public function getLoginUserUrl(){
		$user = $this->getLoginUser();
		return $user['url'];
	}
	//获取登录用户的IP
	public function getIp(){
		load('extend');
		Log::write(get_client_ip());
		return get_client_ip();
	}
	//获取用户
	public function getUser($map){
		$user = $this->where($map)->find();
		if($user){
			unset($user['password']);
			return $user;
		}else{
			return null;
		}
	}
}